package com.itheima.dao.impl;

import com.itheima.dao.DeptDao;

import java.sql.*;

public class DeptDaoImpl implements DeptDao {
    Connection conn = null;
    Statement st =null;

    /**
     * @return
     *2.新增一个部门和员工，员工属于新增的部门
     */
    @Override
    public int addDeptAndEmp() {
        int j =0;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db5", "root", "1234");
            st = conn.createStatement();

//          新增部门
            String deptSql = "INSERT INTO t_dept VALUES (NULL,'人事部'); ";
            int i = st.executeUpdate(deptSql, Statement.RETURN_GENERATED_KEYS);

            ResultSet generatedKeys = st.getGeneratedKeys();
            int anInt = 0;
            while (generatedKeys.next()){
                anInt = generatedKeys.getInt(1);
            }
//          新增员工
            if(anInt!=0){
                String empSql =  "INSERT INTO t_emp VALUES (NULL,'jack',now(),10000,"+anInt+"); ";
                 j = st.executeUpdate(empSql);
            }
//
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (st != null){
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }


}
